package com.example.springsecurity.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.domain.*;
import com.example.springsecurity.security.SecurityUtils;
import com.example.springsecurity.service.*;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.convert.Convert;
import com.example.springsecurity.utils.excel.ExcelUtils;
import com.example.springsecurity.utils.ifnull.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.expression.Lists;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SchoolTeaching
 * @Description TODO     校内教学模块
 * @Author lvyongwei
 * @Date
 **/
@Controller
@RequestMapping("/schoolTeaching")
public class SchoolTeachingController {

    @Autowired
    private ProjectTeachService projectTeachService;

    @Autowired
    private ExperimentService experimentService;

    @Autowired
    private CollegeService collegeService;

    @Autowired
    private AssignExperimentService assignExperimentService;

    @Autowired
    private ExcelUtils excelUtils;


    /**
     * 获取当前登录人(负责人,教师)负责的实验项目
     * @param data   {"pageNum":1,"pageSize":10,"projectName":""}
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:chargeProject')")
    @PostMapping("/getChargeProject")
    @ResponseBody
    public ResultBean getChargeProject(@RequestBody String data){
        /**
         * 获取当前登录人id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String projectName = jsonObject.getString("projectName");
        /**
         * 根据当前登录人id获取所负责的实验
         */
        return projectTeachService.getChargeProject(userId,projectName,pageNum,pageSize);
    }

    /**
     * 负责人,教师点击布置实验返回内容
     * @param projectId
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:assignProject')")
    @PostMapping("/getAssignProject")
    @ResponseBody
    public ResultBean getAssignProject(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer projectId = jsonObject.getInteger("projectId");
        try{
            AssignProject assignProject = experimentService.getAssignProject(projectId);
            return ResultBean.success("成功获取到内容",assignProject);
        }catch (Exception e){
            return ResultBean.error("获取内容失败");
        }
    }


    /**
     * 根据学院，专业，班级去布置获取学生用户
     * @param data    {"collegeId": ,"majorId": ,"tbClassId": }
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:getStudent')")
    @PostMapping("/getStudent")
    @ResponseBody
    public ResultBean getStudent(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer collegeId = jsonObject.getInteger("collegeId");
        Integer majorId = jsonObject.getInteger("majorId");
        Integer tbClassId = jsonObject.getInteger("tbClassId");
        try{
            List<SysUser> sysUsers = collegeService.getStudent(collegeId,majorId,tbClassId);
            return ResultBean.success("获取用户成功",sysUsers);
        }catch (Exception e){
            return ResultBean.error("获取用户失败");
        }
    }


    /**
     * 布置实验给用户
     * @param assignExperiment
    {
    "assignProjectId":1,
    "assignName":"测试实验布置接口",
    "projectBeginTime":"2020-10-12",
    "projectEndTime":"2020-12-12",
    "experimentScore":20,
    "reportScore":50,
    "videoScore":10,
    "exercisesScore":20,
    "schoolYear":"2020秋季",
    "assignChoiceQuestions":[
    {
    "choiceQuestionId":1,
    "choiceQuestionScore":40
    }
    ],
    "assignObjectiveItems":[
    {
    "objectiveItemId":1,
    "objectiveItemScore":60
    }
    ],
    "userName":["lyw","zjh"]
    }
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:assignExperiment')")
    @PostMapping("/assignExperiment")
    @ResponseBody
    public ResultBean assignExperiment(@RequestBody AssignExperiment assignExperiment){
        /**
         * 获取当前布置的人(教师/负责人)id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        assignExperiment.setUserTeacherId(userId);
        try{
            assignExperimentService.assignExperiment(assignExperiment);
            return ResultBean.success("布置实验成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("布置实验失败");
        }
    }


    /**
     * 查看用户(教师/负责人)布置的实验信息
     * @param data   {"assignName":"","pageNum":1,"pageSize":10}
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:checkAssign')")
    @PostMapping("/checkAssign")
    @ResponseBody
    public ResultBean checkAssign(@RequestBody String data){
        /**
         * 获取当前布置的人(教师/负责人)id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 解析参数
         */
        String assignName = jsonObject.getString("assignName");
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer projectId = jsonObject.getInteger("projectId");
        /**
         * 设置分页
         */
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<CheckAssign> checkAssigns = assignExperimentService.getAllCheckAssign(userId,assignName,projectId);
            PageInfo<CheckAssign> pageInfo = new PageInfo<CheckAssign>(checkAssigns);
            return ResultBean.success("返回布置数据成功",pageInfo);
        }catch (Exception e){
            return ResultBean.error("返回布置数据失败");
        }
    }


    /**
     * 获取布置详情,即在列表页点击获取内容
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:getAssignDetails')")
    @PostMapping("/getAssignDetails")
    @ResponseBody
    public ResultBean getAssignDetails(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 解析参数
         */
        Long assignId = jsonObject.getLong("assignId");
        try{
            AssignDetails assignDetails = assignExperimentService.getAssignDetails(assignId);
            return ResultBean.success(assignDetails);
        }catch (Exception e){
            return ResultBean.error("获取详情失败");
        }
    }


    /**
     * 修改本次布置信息
     * @param assignExperiment
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:updateAssign')")
    @PostMapping("/updateAssign")
    @ResponseBody
    public ResultBean updateAssign(@RequestBody AssignExperiment assignExperiment){
        try{
            assignExperimentService.updateAssign(assignExperiment);
            return ResultBean.success("修改成功");
        }catch (Exception e){
            return ResultBean.error("修改失败");
        }
    }

    /**
     * 删除本次布置
     *
     *       目前没有删除某次布置下习题表
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:deleteAssign')")
    @PostMapping("/deleteAssign")
    @ResponseBody
    public ResultBean deleteAssign(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 解析参数
         */
        Long assignId = jsonObject.getLong("assignId");
        try{
            assignExperimentService.deleteAssign(assignId);
            return ResultBean.success("删除成功");
        }catch (Exception e){
            return ResultBean.error("删除失败");
        }
    }


    /**
     * 查询批改，批改列表
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:correct')")
    @PostMapping("/correct")
    @ResponseBody
    public ResultBean correct(@RequestBody String data){
        /**
         * 解析参数,页码，显示条数，必修选修状态，参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String realName = jsonObject.getString("realName");
        Long assignId = jsonObject.getLong("assignId");
        Integer correctStatus = jsonObject.getInteger("correctStatus");
        /**
         * 分页
         */
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        try{
            PageHelper.startPage(pageNum,pageSize);
            List<TeacherCorrectScore> teacherCorrectScores = assignExperimentService.getAllTeacherCorrect(realName,correctStatus,assignId);
            PageInfo<TeacherCorrectScore> pageInfo = new PageInfo<TeacherCorrectScore>(teacherCorrectScores);
            return ResultBean.success("查询批改列表成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("查询批改列表失败");
        }
    }


    /**
     * 教师点击批改后展示成绩内容
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:correctUser')")
    @PostMapping("/correctUser")
    @ResponseBody
    public ResultBean correctUser(@RequestBody String data){
        /**
         * 解析参数,页码，显示条数，必修选修状态，参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer submitId = jsonObject.getInteger("submitId");
        try{
            CorrectUser correctUser = assignExperimentService.getMustScore(submitId);
            return ResultBean.success("获取成绩成功",correctUser);
        }catch (Exception e){
            return ResultBean.error("获取成绩失败");
        }
    }


    /**
     * 批改用户成绩
     * @param teacherCorrectScore
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:correctResult')")
    @PostMapping("/correctResult")
    @ResponseBody
    public ResultBean correctResult(@RequestBody TeacherCorrectScore teacherCorrectScore){
        try{
            assignExperimentService.correctResult(teacherCorrectScore);
            return ResultBean.success("批改成功");
        }catch (Exception e){
            return ResultBean.error("批改失败");
        }
    }


    /**
     * 查看批改结果
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:lookCorrect')")
    @PostMapping("/lookCorrect")
    @ResponseBody
    public ResultBean lookCorrect(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Long assignId = jsonObject.getLong("assignId");
        Integer submitId = jsonObject.getInteger("submitId");
        try{
            TeacherCorrectScore teacherCorrectScore = assignExperimentService.getTeacherCorrectScore(assignId,submitId);
            return ResultBean.success("获取批改结果成功",teacherCorrectScore);
        }catch (Exception e){
            return ResultBean.error("获取批改结果失败");
        }
    }


    /**
     * 撤销批改结果
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:experiment:repealCorrect')")
    @PostMapping("/repealCorrect")
    @ResponseBody
    public ResultBean repealCorrect(@RequestBody String data){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Long assignId = jsonObject.getLong("assignId");
        Integer submitId = jsonObject.getInteger("submitId");
        String userName = jsonObject.getString("userName");
        try{
            assignExperimentService.repealCorrect(assignId,submitId,userName);
            return ResultBean.success("撤销批改结果成功");
        }catch (Exception e){
            return ResultBean.error("撤销批改结果失败");
        }
    }


    /**
     * 导出布置成绩
     * @param request
     * @param response
     * @param assignId
     */
    @GetMapping("/exportScore")
    public void exportScore(HttpServletRequest request, HttpServletResponse response, String assignId) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        Long[] assignIds = Convert.toLongArray(",",assignId);
        try {
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("成绩导出","UTF-8")+".xlsx");
            ExcelWriter writer = null;
            //实例化 ExcelWriter
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);
            for(int i=0;i<assignIds.length;i++){
                List<ExportScore> list = assignExperimentService.exportTeacherCorrect(assignIds[i]);
                //获取名称
                String assignName = assignExperimentService.getAssignDetail(assignIds[i]).getAssignName();
                /**
                 * 设置excel文件中sheet的表头
                 */
                Table table = new Table(i);
                List<List<String>> headList = new ArrayList<>();
                headList.add(new ArrayList<String>(){{add(assignName);add("学号");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("姓名");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("所属班级");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("总成绩");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("视频成绩");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("实验操作成绩");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("实验报告得分");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("提交时间");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("是否提交");}});
                headList.add(new ArrayList<String>(){{add(assignName);add("是否批改");}});
                table.setHead(headList);
                //实例化表单
                Sheet sheet = new Sheet(i+1,0);
                //设置自动宽度和sheet名称
                sheet.setAutoWidth(true);
                sheet.setSheetName("sheet"+i);
                //输出
                writer.write(list, sheet, table);
            }
            writer.finish();
            outputStream.flush();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
